<template>
  <div>
    <div class="search">
      <input
        type="text"
        placeholder="输入城市名或拼音"
        class="search__input"
        v-model="keyword"
      />
    </div>
    <div class="list" v-show="keyword" ref="search">
      <ul>
        <!-- 假如 li 里面有数据就显示，没数据就不显示 -->
        <li
          class="list__item"
          v-for="item in list"
          :key="item.id"
          @click="handleChangeCity(item.name)"
        >
          {{ item.name }}
        </li>
        <li class="list__item" v-show="hasNoData">没有匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  name: "CitySearch",
  props: {
    cities: Object,
  },
  data() {
    return {
      keyword: "",
      timer: null,
      list: [],
    };
  },
  methods: {
    handleChangeCity(city) {
      this.$store.commit("changeCity", city);
      console.log(city);
      // 使用 router.push() 进行路由跳转
      this.$router.push("/");
    },
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    },
  },
  watch: {
    keyword() {
      // 清除重复延时器
      if (this.timer) {
        clearTimeout(this.timer);
      }
      // 输入框为空，list 也应该为空
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            // 在数组中查找输入的值，如果有就放入 result 数组中
            // console.log(value);
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              // console.log(value);
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    },
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.search);
  },
};
</script>

<style lang="scss" scoped>
.search {
  height: 0.64rem;
  padding: 0 0.1rem;
  background-color: #00bcd4;
  &__input {
    box-sizing: border-box;
    padding: 0 0.2rem;
    height: 0.54rem;
    width: 100%;
    line-height: 0.54rem;
    font-size: 0.2rem;
    color: #666;
    text-align: center;
    border-radius: 0.1rem;
  }
}
.list {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.5rem;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #eee;
  &__item {
    line-height: 0.62rem;
    border-bottom: 0.01rem solid #eee;
    background-color: #fff;
    text-indent: 0.2rem;
  }
}
</style>